<template>
    <AppBar title="便签" />
      <div class="editor-wrapper" v-if="editStyleRef.height">
      <div class="edit-title">
        <input v-model="form.name" placeholder="请输入文档标题"        @focus="handleFocus('1')"
        @blur="handleBlur('1')"/>
        <var-icon
          name="window-close"
          :size="14"
          class="clear-icon"
          :style="{ opacity: form.name ? '1' : '0' }"
          @click="form.name = ''"
   
        />
      </div>
      <Editor
        :style="editStyleRef"
        v-model="valueHtmlRef"
        :defaultConfig="editorConfig"
        mode="simple"
        @onCreated="handleCreated"
        @onFocus="handleFocus('2')"
        @onBlur="handleBlur('2')"
      />
    </div>
    <div class="toolbar-box">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        mode="simple"
      />
    </div>
  <var-snackbar v-model:show="msgRef.visible">{{ msgRef.title }}</var-snackbar>
</template>
<script setup name="Edit">
import '@wangeditor/editor/dist/css/style.css'; // 引入 css
import {
  onBeforeUnmount,
  ref,
  reactive,
  shallowRef,
  inject,
  onMounted,
  onUnmounted,
  nextTick,
  watch,
} from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { debounce } from 'lodash';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue';
import useSymbols from '../../../compostions/useSymbols.js'
import AppBar from '../../../components/AppBar/index.vue';

import analysisDoc from '../../../util/analysisDoc.js';

// 自定义菜单
import registerMenu from './customButtons/index.js';
import editToolbarConfig from './toolbarConfig.js';
import editorConfig from './editorConfig.js'

const router = useRouter();
const route = useRoute();

const { editMenoItemFun, getMenoDataItem } = inject(useSymbols);

// 富文本默认的空标签
const unllStr = '<p><br></p>';

const form = reactive({
  name: '',
});
const editStyleRef = ref({});
const msgRef = ref({
  visible: false,
  title: '',
});


const keyboardObj = reactive({
  nameFoucs: false,
  editFoucs:false,
})
watch(keyboardObj, (newKeyboardObj) => {
  if (!newKeyboardObj.nameFoucs && !newKeyboardObj.editFoucs) {
    keyboardHeightRef.value = '6rem';
    getContentHeight();
  } else {
    keyboardHeightRef.value = '23rem';
    getContentHeight();
  }
})

// 软件盘高度
const keyboardHeightRef = ref('6rem');
// 是否初始化
const isInitRef = ref(true);

const handleFocus = (t) => {
  if (isInitRef.value) {
    isInitRef.value = false;
    return;
  }
  switch (t) {
    case '1':
    keyboardObj.nameFoucs = true;
      break;
    case '2':
    keyboardObj.editFoucs = true;
      break;
  }
  
}
const handleBlur = (t) => {
  switch (t) {
    case '1':
    keyboardObj.nameFoucs = false;
      break;
    case '2':
    keyboardObj.editFoucs = false;
      break;
  }
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();

// 内容 HTML
const valueHtmlRef = ref('');
const toolbarConfig = {...editToolbarConfig};

// 记录 editor 实例，重要！
const handleCreated = (editor) => {
  editorRef.value = editor;
  registerMenu(editorRef.value, toolbarConfig); // 注册自定
};

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

onMounted(() => {
  setTimeout(async () => {
    getContentHeight();
    // 有id表示编辑状态
    await nextTick();
    if (route.query.id) {
      const {
        name,
        content,
        createTime = null,
      } = await getMenoDataItem(route.query.id);
      // 富文本设置html
      editorRef.value.setHtml(content);
      // form赋值
      form.name = name;
      form.createTime = createTime;
    }
    isInitRef.value = false;
  }, 200);
  // 阻止浏览器，默认滚动
  window.addEventListener('scroll',preventScroll)
});

onUnmounted(() => {
  // 阻止浏览器，默认滚动
  window.removeEventListener('scroll',preventScroll)
})

const preventScroll = (e) => {
   // 阻止滚动事件
   e.preventDefault();
  document.documentElement.scrollTop = document.body.scrollTop = 0;
}

// 获取富文本内容高度
const getContentHeight = () => {
  editStyleRef.value = {
    overflowY: 'hidden',
    height: `calc(35rem - ${keyboardHeightRef.value})`,
    padding: '0',
    margin: '0',
  };
};

// 保存
const saveValueHtml = debounce(async () => {
  const newHtmlValTrim = valueHtmlRef.value.trim();
  const formName = form.name.trim();
  if (formName === '' || newHtmlValTrim === unllStr) return;
  try {
    const content = valueHtmlRef.value;
    const { describe, src } = analysisDoc(content);
    const param = { content, ...form, describe, src: src || '' };
    if (route.query.id) param.id = route.query.id;

    const res = await editMenoItemFun({ ...param });
    msgRef.value = {
      visible: true,
      title: '保存成功！',
    };

    if(!route.query.id)router.replace({ query: { id: res.data } });
  } catch (error) {
    console.log(error);
  } finally {
    setTimeout(() => {
      msgRef.value.visible = false;
    }, 1000);
  }
}, 3000);

// 监听输入框的辩护，自动保存
watch([valueHtmlRef, () => form.name], (newValues, oldValues) => {
  if (route.query.id && (oldValues[1] === '' || oldValues[0] === unllStr)) return;
  saveValueHtml();
  
});
</script>
<style scoped>
.toolbar-box {
  width: 100%;
  height: 2.4rem;
  position: fixed;
  top: 50px;
  border-top: 1px solid #d9d9d9;
  z-index: 88;
}
.editor-wrapper {
  --upload-width-height: 114px;
  border-radius: 15px;
  overflow: hidden;
  background-color: #ffffff;
  padding:2rem 10px 0;
  height: calc(100% - 5.3rem);
  overflow: hidden;
}
.form-wrapper {
  padding: 16px 16px 0px 16px;
}

.editor-wrapper >>> .avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.editor-wrapper >>> .avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.editor-wrapper >>> .el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: var(--upload-width-height);
  height: var(--upload-width-height);
  text-align: center;
  overflow: hidden;
}

.editor-wrapper >>> .avatar-uploader .avatar {
  width: var(--upload-width-height);
  height: var(--upload-width-height);
  display: block;
  overflow: hidden;
}

.edit-title {
  width: 100%;
  padding: 1rem 0;
  border-bottom: 1px solid #e8e8e8;
  display: grid;
  align-items: center;
  grid-template-columns: 1fr 2rem;
}
.edit-title > .clear-icon {
  border-radius: 50%;
  width: 0.8rem;
  height: 0.8rem;
  background-color: #888;
  color: #fff;
  padding: 0.1rem;
}

.edit-title > input {
  font-size: 26px;
  border: 0;
  outline: none;
  line-height: 1;
  color: #333;
}
.toolbar-box >>> .w-e-bar-divider {
  margin: 0 !important;
  width: 0;
}
.toolbar-box >>> .w-e-bar-item {
  padding: 4px 0.34rem;
}
.toolbar-box>>>.w-e-bar-item-group .w-e-bar-item-menus-container {
    left: -46px;
    top: -87px;
}
.toolbar-box>>>.w-e-drop-panel{
  right: -80px !important;
  left: unset !important;
}
.toolbar-box>>>.w-e-menu-tooltip-v5:before{
  opacity:0 !important;
}
.toolbar-box>>>.w-e-menu-tooltip-v5:after{
  opacity: 0 !important;
}
</style>